package com.zhuojy.equity.mall.admin.service.salary;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhuojy.equity.mall.admin.common.constant.JwtConstants;
import com.zhuojy.equity.mall.admin.common.entity.TPosition;
import com.zhuojy.equity.mall.admin.common.entity.bo.salary.*;
import com.zhuojy.equity.mall.admin.common.entity.po.THolidayPo;
import com.zhuojy.equity.mall.admin.common.entity.po.salary.*;
import com.zhuojy.equity.mall.admin.common.entity.vo.salary.*;
import com.zhuojy.equity.mall.admin.common.utils.FindDateStatusUtil;
import com.zhuojy.equity.mall.admin.dal.mapper.TPositionMapper;
import com.zhuojy.equity.mall.admin.dal.mapper.salary.PaySlipsMapper;
import com.zhuojy.equity.mall.admin.dal.mapper.salary.TSalaryMapper;
import com.zhuojy.equity.mall.admin.manager.token.TokenManager;
import com.zhuojy.equity.mall.admin.service.PositionService;
import com.zhuojy.equity.mall.admin.service.THolidayService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author chen
 * @version 1.0
 * @description: 薪资表的Service层
 * @date 2024/3/27 15:58
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class TSalaryService extends ServiceImpl<TSalaryMapper, TSalaryPO> {
    /**
     * 职位service
     */
    private final PositionService positionService;
    /**
     * 计税规则Service
     */
    private final TaxCalculationRulesService taxCalculationRulesService;
    /**
     * 标准计薪规则Service层
     */
    private final StandardPayrollRulesService standardPayrollRulesService;
    /**
     * 病假扣款规则Service层
     */
    private final SickLeaveRulesService sickLeaveRulesService;
    /**
     * 事假请假规则Service层
     */
    private final PersonalLeaveRulesService personalLeaveRulesService;
    /**
     * 加班规则Service层
     */
    private final OvertimeRulesService overtimeRulesService;
    /**
     * 迟到扣款规则Service层
     */
    private final LateChargeRulesService lateChargeRulesService;
    /**
     * 迟到早退规则Service层
     */
    private final LateArrivalRulesService lateArrivalRulesService;
    /**
     * 早退扣款规则Service层
     */
    private final EarlyRefundDeductionRulesService earlyRefundDeductionRulesService;
    /**
     * 旷工扣款规则Service层
     */
    private final AbsenteeismDeductionRulesService absenteeismDeductionRulesService;
    /**
     * 假期Service层
     */
    private final THolidayService tHolidayService;
    /**
     * 假期Service层
     */
    private final RulesForTheDistributionOfAttendanceAwardsService rulesForTheDistributionOfAttendanceAwardsService;
    @Autowired
    private TokenManager tokenManager;
    /**
     * 薪资方案关联人数ervice层
     */
    private final SalaryWhoService salaryWhoService;
    /**
     * 员工薪资档案Service层
     */
    private final TUserArchivesService tUserArchivesService;
    /**
     * 工资条Service层
     */
    private final PaySlipsMapper paySlipsMapper;

    /**
     * @description: TODO
     * @author 获取部门列表
     * @date 2024-04-01 15:04:17
     * @version 1.0
     */
    public List<TPosition> getDeptList() {
        QueryWrapper<TPosition>  qw  = new QueryWrapper<>();
        qw.select("DISTINCT dept_name");
        List<TPosition> list = positionService.list(qw);
        return list;
    }
    /**
     * @description: 获取假期列表
     * @return java.util.List<com.zhuojy.equity.mall.admin.common.entity.po.THolidayPo>
     * @author chen
     * @date: 2024-04-01 15:04:46
     */
    public List<THolidayPo> getHolidayList() {
        List<THolidayPo> list = tHolidayService.list();
        return list;
    }
    @Transactional(rollbackFor = Exception.class)
    public void addPayrollProposal(TSalaryPO tSalaryPO,
                                   TaxCalculationRulesPO taxCalculationRulesPO,
                                   StandardPayrollRulesPO standardPayrollRulesPO,
                                   SickLeaveRulesPO sickLeaveRulesPO,
                                   RulesForTheDistributionOfAttendanceAwardsPO rulesForTheDistributionOfAttendanceAwardsPO,
                                   PersonalLeaveRulesPO personalLeaveRulesPO,
                                   OvertimeRulesPO overtimeRulesPO,
                                   LateChargeRulesBO lateChargeRulesBO,
                                   LateArrivalRulesPO lateArrivalRulesPO,
                                   EarlyRefundDeductionRulesBO earlyRefundDeductionRulesBO,
                                   AbsenteeismDeductionRulesPO absenteeismDeductionRulesPO,HttpServletRequest request
) {

        // 新增薪资表
        tSalaryPO.setCreateTime(new Date());
        String userNameFromToken = tokenManager.getUserNameFromToken(request.getHeader(JwtConstants.TOKEN_HEADER).substring(6));
        tSalaryPO.setCreateBy(userNameFromToken);
        save(tSalaryPO);
        // 将薪资表的id赋值然后新增
        taxCalculationRulesPO.setSalaryId(tSalaryPO.getId());
        taxCalculationRulesService.save(taxCalculationRulesPO);
        // 将薪资表的id赋值然后新增
        standardPayrollRulesPO.setSalaryId(tSalaryPO.getId());
        standardPayrollRulesService.save(standardPayrollRulesPO);
        // 将薪资表的id赋值然后新增
        sickLeaveRulesPO.setSalaryId(tSalaryPO.getId());
        sickLeaveRulesService.save(sickLeaveRulesPO);
        // 将薪资表的id赋值然后新增
        rulesForTheDistributionOfAttendanceAwardsPO.setSalaryId(tSalaryPO.getId());
        rulesForTheDistributionOfAttendanceAwardsService.save(rulesForTheDistributionOfAttendanceAwardsPO);
        // 将薪资表的id赋值然后新增
        personalLeaveRulesPO.setSalaryId(tSalaryPO.getId());
        personalLeaveRulesService.save(personalLeaveRulesPO);
        // 将薪资表的id赋值然后新增
        overtimeRulesPO.setSalaryId(tSalaryPO.getId());
        overtimeRulesService.save(overtimeRulesPO);

        List<LateChargeRulesPO> list = new ArrayList<>();
        String[] lateInterval = lateChargeRulesBO.getLateInterval();
        // 处理字符串空格
        for (int i = 0; i < lateInterval.length; i++) {
            // 获取区间前两位
            if(i < 1){
                LateChargeRulesPO lateChargeRulesPO = new LateChargeRulesPO();
                lateChargeRulesPO.setLateInterval(lateInterval[i]);
                lateChargeRulesPO.setLateDeductionRules(lateChargeRulesBO.getLateDeductionRules()[0]);
                lateChargeRulesPO.setLateUnit(lateChargeRulesBO.getLateUnit()[0]);
                // 将处理好的对象放入集合中
                list.add(lateChargeRulesPO);
            }else {
                LateChargeRulesPO lateChargeRulesPO = new LateChargeRulesPO();
                lateChargeRulesPO.setLateInterval(lateInterval[i].trim());
                lateChargeRulesPO.setLateDeductionRules(Integer.parseInt(lateChargeRulesBO.getLateDeductionRules()[1].toString().trim()));
                lateChargeRulesPO.setLateUnit(Integer.parseInt(lateChargeRulesBO.getLateUnit()[1].toString().trim()));
                // 将处理好的对象放入集合中
                list.add(lateChargeRulesPO);
            }
        }
        List<EarlyRefundDeductionRulesPO> list1 = new ArrayList<>();
        String[] earlyInterval = earlyRefundDeductionRulesBO.getEarlyInterval();
        // 处理字符串空格
        for (int i = 0; i < earlyInterval.length; i++) {
            // 获取区间前两位
            if(i < 1){
                EarlyRefundDeductionRulesPO earlyRefundDeductionRulesPO = new EarlyRefundDeductionRulesPO();
                earlyRefundDeductionRulesPO.setEarlyInterval(earlyInterval[i]);
                earlyRefundDeductionRulesPO.setEarlyDeductionRules(earlyRefundDeductionRulesBO.getEarlyDeductionRules()[0]);
                earlyRefundDeductionRulesPO.setEarlyUnit(earlyRefundDeductionRulesBO.getEarlyUnit()[0]);
                // 将处理好的对象放入集合中
                list1.add(earlyRefundDeductionRulesPO);
            }else {
                EarlyRefundDeductionRulesPO earlyRefundDeductionRulesPO = new EarlyRefundDeductionRulesPO();
                earlyRefundDeductionRulesPO.setEarlyInterval(earlyRefundDeductionRulesBO.getEarlyInterval()[i].toString().trim());
                earlyRefundDeductionRulesPO.setEarlyDeductionRules(Integer.parseInt(earlyRefundDeductionRulesBO.getEarlyDeductionRules()[1].toString().trim()));
                earlyRefundDeductionRulesPO.setEarlyUnit(Integer.parseInt(earlyRefundDeductionRulesBO.getEarlyUnit()[1].toString().trim()));
                // 将处理好的对象放入集合中
                list1.add(earlyRefundDeductionRulesPO);
            }
        }

        for (int i = 0; i < list.size(); i++) {
            lateChargeRulesService.save(list.get(i));
            lateArrivalRulesPO.setSalaryId(tSalaryPO.getId());
            lateArrivalRulesPO.setLateChargeRulesId(list.get(i).getLateChargeId());
            earlyRefundDeductionRulesService.save(list1.get(i));
            lateArrivalRulesPO.setEarlyRefundDeductionRulesId(list1.get(i).getEarlyId());
            lateArrivalRulesService.save(lateArrivalRulesPO);
            lateArrivalRulesPO.setLateId(null);
        }
        absenteeismDeductionRulesPO.setSalaryId(tSalaryPO.getId());
        absenteeismDeductionRulesService.save(absenteeismDeductionRulesPO);
    }

    public Map getSalaryList(TSalaryBO tSalaryBO) {
        IPage<TSalaryPO> page = new Page(tSalaryBO.getCurrentPage(),tSalaryBO.getPageSize());
        LambdaQueryWrapper<TSalaryPO> lqw = Wrappers.lambdaQuery();
        if(StringUtils.isNotEmpty(tSalaryBO.getSchemeName())){
            lqw.like(TSalaryPO::getSchemeName,tSalaryBO.getSchemeName());
        }
        page= page(page,lqw);
        // Java获取当前年份、月份和日期是通过Calendar类的实例对象来获取的。
        Calendar calendar = Calendar.getInstance();
        // 获取本年
        int year = calendar.get(Calendar.YEAR);
        List<TSalaryPO> records = page.getRecords();

        List<TSalaryVO> tSalaryVOS = records.stream().map(tSalaryPO -> {
            TSalaryVO tSalaryVO = new TSalaryVO();
            BeanUtils.copyProperties(tSalaryPO, tSalaryVO);
            // 1:上上月 2:上月 3:本月 4:下月 5:下下月
            // 薪资周期
            int salaryCycle = 0;

            if (tSalaryPO.getSalaryCycle() == 1) {
                // 获取上上月
                salaryCycle = calendar.get(Calendar.MONTH) - 1;
            } else if (tSalaryPO.getSalaryCycle() == 2) {
                // 获取上月
                salaryCycle = calendar.get(Calendar.MONTH);
            } else if (tSalaryPO.getSalaryCycle() == 3) {
                // 获取本月
                salaryCycle = calendar.get(Calendar.MONTH) + 1;
            } else if (tSalaryPO.getSalaryCycle() == 4) {
                // 获取下月
                salaryCycle = calendar.get(Calendar.MONTH) + 2;
            } else if (tSalaryPO.getSalaryCycle() == 5) {
                // 获取下下月
                salaryCycle = calendar.get(Calendar.MONTH) + 3;
            }
            tSalaryVO.setSalaryCycle(year + "/" + salaryCycle + "/" + tSalaryPO.getSalaryDays() + "-" + salaryCycle + "/30");
            // 税款周期
            int taxPeriod = 0;
            if (tSalaryPO.getTaxPeriod() == 1) {
                // 获取上上月
                taxPeriod = calendar.get(Calendar.MONTH) - 1;
            } else if (tSalaryPO.getTaxPeriod() == 2) {
                // 获取上月
                taxPeriod = calendar.get(Calendar.MONTH);
            } else if (tSalaryPO.getTaxPeriod() == 3) {
                // 获取本月
                taxPeriod = calendar.get(Calendar.MONTH) + 1;
            } else if (tSalaryPO.getTaxPeriod() == 4) {
                // 获取下月
                taxPeriod = calendar.get(Calendar.MONTH) + 2;
            } else if (tSalaryPO.getTaxPeriod() == 5) {
                // 获取下下月
                taxPeriod = calendar.get(Calendar.MONTH) + 3;
            }
            tSalaryVO.setTaxPeriod(year + "/" + taxPeriod);

            return tSalaryVO;
        }).collect(Collectors.toList());
        Map map = new HashMap();
        map.put("total",page.getTotal());
        map.put("rows",tSalaryVOS);
        return map;
    }

    public SalaryEchoVO findSalary(Long id) {
        SalaryEchoVO salaryEchoVO = new SalaryEchoVO();
        TSalaryPO tSalaryPO = getOne(Wrappers.lambdaQuery(TSalaryPO.class).eq(TSalaryPO::getId, id));
        BeanUtils.copyProperties(tSalaryPO,salaryEchoVO);

        TaxCalculationRulesPO taxCalculationRulesPO = taxCalculationRulesService.getOne(Wrappers.lambdaQuery(TaxCalculationRulesPO.class).eq(TaxCalculationRulesPO::getSalaryId, id));
        salaryEchoVO.setTaxCalculationRulesPO(taxCalculationRulesPO);

        StandardPayrollRulesPO standardPayrollRulesPO = standardPayrollRulesService.getOne(Wrappers.lambdaQuery(StandardPayrollRulesPO.class).eq(StandardPayrollRulesPO::getSalaryId, id));
        salaryEchoVO.setStandardPayrollRulesPO(standardPayrollRulesPO);

        SickLeaveRulesPO sickLeaveRulesPO = sickLeaveRulesService.getOne(Wrappers.lambdaQuery(SickLeaveRulesPO.class).eq(SickLeaveRulesPO::getSalaryId, id));
        salaryEchoVO.setSickLeaveRulesPO(sickLeaveRulesPO);

        RulesForTheDistributionOfAttendanceAwardsPO rulesForTheDistributionOfAttendanceAwardsPO = rulesForTheDistributionOfAttendanceAwardsService.getOne(Wrappers.lambdaQuery(RulesForTheDistributionOfAttendanceAwardsPO.class).eq(RulesForTheDistributionOfAttendanceAwardsPO::getSalaryId, id));
        salaryEchoVO.setRulesForTheDistributionOfAttendanceAwardsPO(rulesForTheDistributionOfAttendanceAwardsPO);

        PersonalLeaveRulesPO personalLeaveRulesPO = personalLeaveRulesService.getOne(Wrappers.lambdaQuery(PersonalLeaveRulesPO.class).eq(PersonalLeaveRulesPO::getSalaryId, id));
        salaryEchoVO.setPersonalLeaveRulesPO(personalLeaveRulesPO);

        OvertimeRulesPO overtimeRulesPO = overtimeRulesService.getOne(Wrappers.lambdaQuery(OvertimeRulesPO.class).eq(OvertimeRulesPO::getSalaryId, id));
        salaryEchoVO.setOvertimeRulesPO(overtimeRulesPO);

        List<LateArrivalRulesPO> lateArrivalRulesPOList = lateArrivalRulesService.list(Wrappers.lambdaQuery(LateArrivalRulesPO.class).eq(LateArrivalRulesPO::getSalaryId, id));
        salaryEchoVO.setLateArrivalRulesPO(lateArrivalRulesPOList);

        List<LateChargeRulesPO> lateChargeRulesPOList = new ArrayList<>();
        List<EarlyRefundDeductionRulesPO> earlyRefundDeductionRulesPOList = new ArrayList<>();
        for (LateArrivalRulesPO lateArrivalRulesPO : lateArrivalRulesPOList) {
            LateChargeRulesPO lateChargeRulesPO = lateChargeRulesService.getOne(Wrappers.lambdaQuery(LateChargeRulesPO.class).eq(LateChargeRulesPO::getLateChargeId, lateArrivalRulesPO.getLateChargeRulesId()));
            EarlyRefundDeductionRulesPO earlyRefundDeductionRulesPO = earlyRefundDeductionRulesService.getOne(Wrappers.lambdaQuery(EarlyRefundDeductionRulesPO.class).eq(EarlyRefundDeductionRulesPO::getEarlyId, lateArrivalRulesPO.getEarlyRefundDeductionRulesId()));
            lateChargeRulesPOList.add(lateChargeRulesPO);
            earlyRefundDeductionRulesPOList.add(earlyRefundDeductionRulesPO);
        }
        salaryEchoVO.setLateChargeRulesPO(lateChargeRulesPOList);
        salaryEchoVO.setEarlyRefundDeductionRulesPO(earlyRefundDeductionRulesPOList);
        AbsenteeismDeductionRulesPO absenteeismDeductionRulesPO = absenteeismDeductionRulesService.getOne(Wrappers.lambdaQuery(AbsenteeismDeductionRulesPO.class).eq(AbsenteeismDeductionRulesPO::getSalaryId, id));
        salaryEchoVO.setAbsenteeismDeductionRulesPO(absenteeismDeductionRulesPO);

        return salaryEchoVO;
    }
    @Transactional(rollbackFor = Exception.class)
    public void updateSalary(TSalaryPO tSalaryPO,
                             TaxCalculationRulesPO taxCalculationRulesPO,
                             StandardPayrollRulesPO standardPayrollRulesPO,
                             SickLeaveRulesPO sickLeaveRulesPO,
                             RulesForTheDistributionOfAttendanceAwardsPO rulesForTheDistributionOfAttendanceAwardsPO,
                             PersonalLeaveRulesPO personalLeaveRulesPO,
                             OvertimeRulesPO overtimeRulesPO,
                             LateChargeRulesBO lateChargeRulesBO,
                             LateArrivalRulesBO lateArrivalRulesBO,
                             EarlyRefundDeductionRulesBO earlyRefundDeductionRulesBO,
                             AbsenteeismDeductionRulesPO absenteeismDeductionRulesPO,
                             HttpServletRequest request) {
        tSalaryPO.setUpdateTime(new Date());
        String userNameFromToken = tokenManager.getUserNameFromToken(request.getHeader(JwtConstants.TOKEN_HEADER).substring(6));
        tSalaryPO.setUpdateBy(userNameFromToken);
        updateById(tSalaryPO);
        taxCalculationRulesService.updateById(taxCalculationRulesPO);
        sickLeaveRulesService.updateById(sickLeaveRulesPO);
        rulesForTheDistributionOfAttendanceAwardsService.updateById(rulesForTheDistributionOfAttendanceAwardsPO);
        personalLeaveRulesService.updateById(personalLeaveRulesPO);
        overtimeRulesService.updateById(overtimeRulesPO);
        List<LateChargeRulesPO> list = new ArrayList<>();
        String[] lateInterval = lateChargeRulesBO.getLateInterval();
        // 处理字符串空格
        for (int i = 0; i < lateInterval.length; i++) {
            // 获取区间前两位
            if(i < 1){
                LateChargeRulesPO lateChargeRulesPO = new LateChargeRulesPO();
                lateChargeRulesPO.setLateChargeId(lateChargeRulesBO.getLateChargeId()[0]);
                lateChargeRulesPO.setLateInterval(lateInterval[i]);
                lateChargeRulesPO.setLateDeductionRules(lateChargeRulesBO.getLateDeductionRules()[0]);
                lateChargeRulesPO.setLateUnit(lateChargeRulesBO.getLateUnit()[0]);
                // 将处理好的对象放入集合中
                list.add(lateChargeRulesPO);
            }else {
                LateChargeRulesPO lateChargeRulesPO = new LateChargeRulesPO();
                lateChargeRulesPO.setLateChargeId(lateChargeRulesBO.getLateChargeId()[1]);
                lateChargeRulesPO.setLateInterval(lateInterval[i].trim());
                lateChargeRulesPO.setLateDeductionRules(Integer.parseInt(lateChargeRulesBO.getLateDeductionRules()[1].toString().trim()));
                lateChargeRulesPO.setLateUnit(Integer.parseInt(lateChargeRulesBO.getLateUnit()[1].toString().trim()));
                // 将处理好的对象放入集合中
                list.add(lateChargeRulesPO);
            }
        }
        lateChargeRulesService.updateBatchById(list);
        List<EarlyRefundDeductionRulesPO> list1 = new ArrayList<>();
        String[] earlyInterval = earlyRefundDeductionRulesBO.getEarlyInterval();
        // 处理字符串空格
        for (int i = 0; i < earlyInterval.length; i++) {
            // 获取区间前两位
            if(i < 1){
                EarlyRefundDeductionRulesPO earlyRefundDeductionRulesPO = new EarlyRefundDeductionRulesPO();
                earlyRefundDeductionRulesPO.setEarlyId(earlyRefundDeductionRulesBO.getEarlyId()[0]);
                earlyRefundDeductionRulesPO.setEarlyInterval(earlyInterval[i]);
                earlyRefundDeductionRulesPO.setEarlyDeductionRules(earlyRefundDeductionRulesBO.getEarlyDeductionRules()[0]);
                earlyRefundDeductionRulesPO.setEarlyUnit(earlyRefundDeductionRulesBO.getEarlyUnit()[0]);
                // 将处理好的对象放入集合中
                list1.add(earlyRefundDeductionRulesPO);
            }else {
                EarlyRefundDeductionRulesPO earlyRefundDeductionRulesPO = new EarlyRefundDeductionRulesPO();
                earlyRefundDeductionRulesPO.setEarlyId(earlyRefundDeductionRulesBO.getEarlyId()[1]);
                earlyRefundDeductionRulesPO.setEarlyInterval(earlyRefundDeductionRulesBO.getEarlyInterval()[i].toString().trim());
                earlyRefundDeductionRulesPO.setEarlyDeductionRules(Integer.parseInt(earlyRefundDeductionRulesBO.getEarlyDeductionRules()[1].toString().trim()));
                earlyRefundDeductionRulesPO.setEarlyUnit(Integer.parseInt(earlyRefundDeductionRulesBO.getEarlyUnit()[1].toString().trim()));
                // 将处理好的对象放入集合中
                list1.add(earlyRefundDeductionRulesPO);
            }
        }
        earlyRefundDeductionRulesService.updateBatchById(list1);
        List<LateArrivalRulesPO> lateArrivalRulesPOList = new ArrayList<>();
        Long[] lateId = lateArrivalRulesBO.getLateId();
        for (int i = 0; i < lateId.length; i++) {
            LateArrivalRulesPO lateArrivalRulesPO = new LateArrivalRulesPO();
            lateArrivalRulesPO.setLateId(lateId[i]);
            lateArrivalRulesPO.setDeductionMethod(lateArrivalRulesBO.getDeductionMethod());
            lateArrivalRulesPO.setSalaryId(lateArrivalRulesBO.getSalaryId());
            lateArrivalRulesPOList.add(lateArrivalRulesPO);
        }
        lateArrivalRulesService.updateBatchById(lateArrivalRulesPOList);
        absenteeismDeductionRulesService.updateById(absenteeismDeductionRulesPO);
    }
    @Transactional(rollbackFor = Exception.class)
    public void stopSalary(Long id) {
        update(Wrappers.lambdaUpdate(TSalaryPO.class).eq(TSalaryPO::getId,id).set(TSalaryPO::getState,4));
    }

    public void deleteSalary(Long id) {
        remove(Wrappers.lambdaQuery(TSalaryPO.class).eq(TSalaryPO::getId,id));
        taxCalculationRulesService.remove(Wrappers.lambdaQuery(TaxCalculationRulesPO.class).eq(TaxCalculationRulesPO::getSalaryId,id));
        sickLeaveRulesService.remove(Wrappers.lambdaQuery(SickLeaveRulesPO.class).eq(SickLeaveRulesPO::getSalaryId,id));
        standardPayrollRulesService.remove(Wrappers.lambdaQuery(StandardPayrollRulesPO.class).eq(StandardPayrollRulesPO::getSalaryId,id));
        rulesForTheDistributionOfAttendanceAwardsService.remove(Wrappers.lambdaQuery(RulesForTheDistributionOfAttendanceAwardsPO.class).eq(RulesForTheDistributionOfAttendanceAwardsPO::getSalaryId,id));
        personalLeaveRulesService.remove(Wrappers.lambdaQuery(PersonalLeaveRulesPO.class).eq(PersonalLeaveRulesPO::getSalaryId,id));
        overtimeRulesService.remove(Wrappers.lambdaQuery(OvertimeRulesPO.class).eq(OvertimeRulesPO::getSalaryId,id));
        List<LateArrivalRulesPO> list = lateArrivalRulesService.list(Wrappers.lambdaQuery(LateArrivalRulesPO.class).eq(LateArrivalRulesPO::getSalaryId, id));
        for (LateArrivalRulesPO lateArrivalRulesPO : list) {
            lateChargeRulesService.remove(Wrappers.lambdaQuery(LateChargeRulesPO.class).eq(LateChargeRulesPO::getLateChargeId,lateArrivalRulesPO.getLateChargeRulesId()));
            earlyRefundDeductionRulesService.remove(Wrappers.lambdaQuery(EarlyRefundDeductionRulesPO.class).eq(EarlyRefundDeductionRulesPO::getEarlyId,lateArrivalRulesPO.getEarlyRefundDeductionRulesId()));

        }
        lateArrivalRulesService.remove(Wrappers.lambdaQuery(LateArrivalRulesPO.class).eq(LateArrivalRulesPO::getSalaryId,id));
        absenteeismDeductionRulesService.remove(Wrappers.lambdaQuery(AbsenteeismDeductionRulesPO.class).eq(AbsenteeismDeductionRulesPO::getSalaryId,id));
    }

    public Map getSalaryCount(Long id) {
        Map map = new HashMap();
        List<SalaryWhoPO> list = salaryWhoService.list(Wrappers.lambdaQuery(SalaryWhoPO.class).eq(SalaryWhoPO::getSalaryId,id));
        // 新入职
        int count = 0;
        // 试用期
        int count1 = 0;
        // 正式员工
        int count2 = 0;
        if (CollectionUtils.isNotEmpty(list)){
            List<Long> collect = list.stream().map(SalaryWhoPO::getUserId).collect(Collectors.toList());
            List<TUserArchivesPO> list1 = tUserArchivesService.listByIds(collect);
            for (TUserArchivesPO tUserArchivesPO : list1) {
                if (tUserArchivesPO.getOnboardingTime() != null) {
                    boolean thisMonth = FindDateStatusUtil.isThisMonth(tUserArchivesPO.getOnboardingTime());
                    if (thisMonth) {
                        count++;
                    }
                }
                if (tUserArchivesPO.getEmployeeStatus() == 1){
                    count1++;
                }
                if (tUserArchivesPO.getEmployeeStatus() == 2){
                    count2++;
                }
            }
        }
        // 计薪人数
        map.put("salariedPeople",list.size());
        // 新入职
        map.put("newHires",count);
        // 试用期
        map.put("probationPeriod",count1);
        // 正式员工
        map.put("formal",count2);
        return map;
    }

    public List<TUserArchivesVO> findNotAddedUserList(Long id) {
        TSalaryPO one = getOne(Wrappers.lambdaQuery(TSalaryPO.class).eq(TSalaryPO::getId, id));
        String deptId = one.getDeptId();
        List<TPosition> list = positionService.list(Wrappers.lambdaQuery(TPosition.class).eq(TPosition::getDeptName, deptId));
        List<Long> collect = list.stream().map(TPosition::getId).collect(Collectors.toList());

        List<SalaryWhoPO> list1 = salaryWhoService.list(Wrappers.lambdaQuery(SalaryWhoPO.class).eq(SalaryWhoPO::getSalaryId, id));
        List<Long> collect1 = list1.stream().map(SalaryWhoPO::getUserId).collect(Collectors.toList());

        LambdaQueryWrapper<TUserArchivesPO> lqw = Wrappers.lambdaQuery(TUserArchivesPO.class);
        if(CollectionUtils.isNotEmpty(collect1)){
            lqw.notIn(TUserArchivesPO::getUserId, collect1);
        }
        if(CollectionUtils.isNotEmpty(collect)){
            lqw.in(TUserArchivesPO::getPositionId, collect);
        }


        List<TUserArchivesPO> tUserArchivesPOS = tUserArchivesService.list(lqw);
        List<TUserArchivesVO> tUserArchivesVOS = tUserArchivesPOS.stream().map(tUserArchivesPO -> {
            TUserArchivesVO tUserArchivesVO = new TUserArchivesVO();
            BeanUtils.copyProperties(tUserArchivesPO, tUserArchivesVO);
            TPosition tPosition = positionService.getOne(Wrappers.lambdaQuery(TPosition.class).eq(TPosition::getId, tUserArchivesPO.getPositionId()));
            tUserArchivesVO.setDeptName(tPosition.getDeptName());
            tUserArchivesVO.setPositionName(tPosition.getPositionName());
            return tUserArchivesVO;
        }).collect(Collectors.toList());
        return tUserArchivesVOS;
    }
    @Transactional(rollbackFor = Exception.class)
    public void addPeople(AddPeopleBO addPeopleBO) {
        for (Long aLong : addPeopleBO.getUserId()) {
            SalaryWhoPO salaryWhoPO = new SalaryWhoPO();
            salaryWhoPO.setUserId(aLong);
            salaryWhoPO.setSalaryId(addPeopleBO.getId());
            salaryWhoService.save(salaryWhoPO);
            salaryWhoPO.setId(null);
        }
    }

    public Map findSalaryByIdList(TUserArchivesBO tUserArchivesBO) {
        List<SalaryWhoPO> list = salaryWhoService.list(Wrappers.lambdaQuery(SalaryWhoPO.class).eq(SalaryWhoPO::getSalaryId, tUserArchivesBO.getId()));
        LambdaQueryWrapper<TUserArchivesPO> lqw = Wrappers.lambdaQuery(TUserArchivesPO.class);

        List<Long> userIdList = list.stream().map(SalaryWhoPO::getUserId).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(userIdList)){
            lqw.in(TUserArchivesPO::getUserId,userIdList);
        }else{
            Map map = new HashMap();
            map.put("rows",null);
            map.put("total",null);
            return  map;
        }

        if (StringUtils.isNotEmpty(tUserArchivesBO.getName())){
            lqw.like(TUserArchivesPO::getName,tUserArchivesBO.getName());
        }

        if(tUserArchivesBO.getEmployeeStatus() != 0 && tUserArchivesBO.getEmployeeStatus() != null){
            lqw.eq(TUserArchivesPO::getEmployeeStatus,tUserArchivesBO.getEmployeeStatus());
        }
        TSalaryPO tSalaryPO = getOne(Wrappers.lambdaQuery(TSalaryPO.class).eq(TSalaryPO::getId, tUserArchivesBO.getId()));
        List<Long> id = positionService.list(Wrappers.lambdaQuery(TPosition.class).eq(TPosition::getDeptName, tSalaryPO.getDeptId())).stream().map(TPosition::getId).collect(Collectors.toList());
        lqw.in(TUserArchivesPO::getPositionId,id);



        IPage<TUserArchivesPO> page = new Page<>(tUserArchivesBO.getCurrentPage(),tUserArchivesBO.getPageSize());
        page = tUserArchivesService.page(page,lqw);
        List<TUserArchivesPO> tUserArchivesPOS = page.getRecords();

        List<TUserArchivesVO> tUserArchivesVOS = tUserArchivesPOS.stream().map(tUserArchivesPO -> {
            TUserArchivesVO tUserArchivesVO = new TUserArchivesVO();
            BeanUtils.copyProperties(tUserArchivesPO, tUserArchivesVO);
            TPosition tPosition = positionService.getOne(Wrappers.lambdaQuery(TPosition.class).eq(TPosition::getId, tUserArchivesPO.getPositionId()));
            tUserArchivesVO.setDeptName(tPosition.getDeptName());
            tUserArchivesVO.setPositionName(tPosition.getPositionName());
            return tUserArchivesVO;
        }).collect(Collectors.toList());
        Map map = new HashMap();
        map.put("rows",tUserArchivesVOS);
        map.put("total",page.getTotal());
        return map;

    }

    public void removePeople(TUserArchivesBO tUserArchivesBO) {
        salaryWhoService.remove(Wrappers.lambdaQuery(SalaryWhoPO.class).eq(SalaryWhoPO::getSalaryId,tUserArchivesBO.getId()).in(SalaryWhoPO::getUserId,tUserArchivesBO.getUserId()));
    }

    public Map getPayrollList(PaySlipsBO paySlipsBO) {
        IPage<PaySlipsPO> page =new Page<>(paySlipsBO.getCurrentPage(),paySlipsBO.getPageSize());
        LambdaQueryWrapper<PaySlipsPO> lqw = Wrappers.lambdaQuery(PaySlipsPO.class);
        if (StringUtils.isNotEmpty(paySlipsBO.getPaySlipsName())){
            lqw.like(PaySlipsPO::getPaySlipsName,paySlipsBO.getPaySlipsName());
        }
        lqw.ne(PaySlipsPO::getState,2);
        page = paySlipsMapper.selectPage(page,lqw);

        List<PaySlipsPO> records = page.getRecords();
        List<PayrollVO> payrollVOS = records.stream().map(paySlipsPO -> {
            PayrollVO paySlipsVO = new PayrollVO();
            paySlipsVO.setPaySlipsId(paySlipsPO.getId());
            paySlipsVO.setPaySlipsName(paySlipsPO.getPaySlipsName());
            paySlipsVO.setSalaryId(paySlipsPO.getSalaryId());
            paySlipsVO.setCreateTime(paySlipsPO.getCreateTime());
            // 查询总人数
            long count = salaryWhoService.count(Wrappers.lambdaQuery(SalaryWhoPO.class).eq(SalaryWhoPO::getSalaryId, paySlipsPO.getSalaryId()));
            paySlipsVO.setPeopleCount(count);
            // 查询确认状态人数
            long cnfirmTheStatus = salaryWhoService.count(Wrappers.lambdaQuery(SalaryWhoPO.class).eq(SalaryWhoPO::getSalaryId, paySlipsPO.getSalaryId()).eq(SalaryWhoPO::getConfirmTheStatus, 2));
            paySlipsVO.setConfirmTheStatus(cnfirmTheStatus);
            // 查询已发送人数
            long issuanceStatus = salaryWhoService.count(Wrappers.lambdaQuery(SalaryWhoPO.class).eq(SalaryWhoPO::getSalaryId, paySlipsPO.getSalaryId()).eq(SalaryWhoPO::getIssuanceStatus, 4));
            paySlipsVO.setIssuanceStatus(issuanceStatus);
            return paySlipsVO;
        }).collect(Collectors.toList());

        Map map = new HashMap();
        map.put("rows", payrollVOS);
        map.put("total",page.getTotal());
        return map;
    }

    public Map getPayrollCount(Long id) {
        Map map = new HashMap();
        // 总人数
        long countPeople = salaryWhoService.count(Wrappers.lambdaQuery(SalaryWhoPO.class).eq(SalaryWhoPO::getSalaryId, id));
        map.put("countPeople",countPeople);
        // 已发送数量
        long sent = salaryWhoService.count(Wrappers.lambdaQuery(SalaryWhoPO.class).eq(SalaryWhoPO::getSalaryId, id).eq(SalaryWhoPO::getIssuanceStatus, 4));
        map.put("sent",sent);
        // 未发送数量
        long notSent = salaryWhoService.count(Wrappers.lambdaQuery(SalaryWhoPO.class).eq(SalaryWhoPO::getSalaryId, id).eq(SalaryWhoPO::getIssuanceStatus, 1));
        map.put("notSent",notSent);
        // 已撤回数量
        long withdrawn = salaryWhoService.count(Wrappers.lambdaQuery(SalaryWhoPO.class).eq(SalaryWhoPO::getSalaryId, id).eq(SalaryWhoPO::getIssuanceStatus, 3));
        map.put("withdrawn",withdrawn);
        // 已确认数量
        long confirmed = salaryWhoService.count(Wrappers.lambdaQuery(SalaryWhoPO.class).eq(SalaryWhoPO::getSalaryId, id).eq(SalaryWhoPO::getConfirmTheStatus, 2));
        map.put("confirmed",confirmed);
        // 未确认数量
        long notConfirmed = salaryWhoService.count(Wrappers.lambdaQuery(SalaryWhoPO.class).eq(SalaryWhoPO::getSalaryId, id).eq(SalaryWhoPO::getConfirmTheStatus, 1));
        map.put("notConfirmed",notConfirmed);

        return map;
    }

    public Map getPayrollPeopleList(PayrollBO payrollBO) {
        List<SalaryWhoPO> list = salaryWhoService.list(Wrappers.lambdaQuery(SalaryWhoPO.class).eq(SalaryWhoPO::getSalaryId, payrollBO.getSalaryId()));

        IPage<TUserArchivesPO> page = new Page<>(payrollBO.getCurrentPage(),payrollBO.getPageSize());

        LambdaQueryWrapper<TUserArchivesPO> lqw = Wrappers.lambdaQuery(TUserArchivesPO.class);

        if(StringUtils.isNotEmpty(payrollBO.getName())){
            lqw.like(TUserArchivesPO::getName, payrollBO.getName());
        }

        if (CollectionUtils.isNotEmpty(list)){
            List<Long> userId = list.stream().map(SalaryWhoPO::getUserId).collect(Collectors.toList());
            lqw.in(TUserArchivesPO::getUserId,userId);
        }
        page = tUserArchivesService.page(page,lqw);

        List<TUserArchivesPO> tUserArchivesPOS = page.getRecords();

        List<PayrollPeopleLIstVO> payrollPeopleLIstVOS = tUserArchivesPOS.stream().map(tUserArchivesPO -> {
            PayrollPeopleLIstVO payrollPeopleLIstVO = new PayrollPeopleLIstVO();
            payrollPeopleLIstVO.setSalaryId(payrollBO.getSalaryId());
            BeanUtils.copyProperties(tUserArchivesPO, payrollPeopleLIstVO);
            SalaryWhoPO salaryWhoPO = salaryWhoService.getOne(Wrappers.lambdaQuery(SalaryWhoPO.class)
                    .eq(SalaryWhoPO::getSalaryId, payrollBO.getSalaryId())
                    .eq(SalaryWhoPO::getUserId, tUserArchivesPO.getUserId()));
            TPosition tPosition= positionService.getOne(Wrappers.lambdaQuery(TPosition.class).eq(TPosition::getId, tUserArchivesPO.getPositionId()));
            payrollPeopleLIstVO.setDeptName(tPosition.getDeptName());
            payrollPeopleLIstVO.setPositionName(tPosition.getPositionName());

            payrollPeopleLIstVO.setIssuanceStatus(salaryWhoPO.getIssuanceStatus());
            payrollPeopleLIstVO.setConfirmTheStatus(salaryWhoPO.getConfirmTheStatus());
            return payrollPeopleLIstVO;
        }).collect(Collectors.toList());
        Map map = new HashMap();
        map.put("rows",payrollPeopleLIstVOS);
        map.put("total",page.getTotal());

        return map;
    }
}
